package com.trf.servlet.user;

import com.trf.pojo.User;
import com.trf.service.user.UserService;
import com.trf.service.user.UserServiceImpl;
import com.trf.util.Constants;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author 唐荣锋
 * @Date 2022/3/9-星期三-18:34
 */
public class LoginServlet extends HttpServlet {

    //Servlet：控制层，调用业务层代码
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
//      测试  System.out.println("LoginServlet进入无问题！");
        //获取用户名和密码,注意！注意！注意！此时是获取前端login页面中的 name="userCode" name="userPassword" 值
        String userCode = req.getParameter("userCode");
        String userPassword = req.getParameter("userPassword");

        //与数据库中的密码进行对比，调用业务层
        UserService userService = new UserServiceImpl();
        User user = userService.login(userCode, userPassword);//这里已经把登录的人查出来了
//        System.out.println(userCode);
//        System.out.println(userPassword);
        if (user!=null){//如果数据库查询正确，则可以登录
            //将用户的信息放到Session中
            req.getSession().setAttribute(Constants.USER_SESSION,user);
            //跳转到主页
            resp.sendRedirect("jsp/frame.jsp");
        }else {//数据库查询失败（没有该用户），无法登录
            //转发回登录页面，顺带提示，用户名或者密码错误
            req.setAttribute("error","用户名或密码不正确");
            req.getRequestDispatcher("login.jsp").forward(req,resp);
        }
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req,resp);
    }
}
